/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufsc.aps.jogodavida.view;

import br.ufsc.aps.jogodavida.control.AtorJogador;
import br.ufsc.inf.leobr.cliente.exception.ArquivoMultiplayerException;
import br.ufsc.inf.leobr.cliente.exception.JahConectadoException;
import br.ufsc.inf.leobr.cliente.exception.NaoConectadoException;
import br.ufsc.inf.leobr.cliente.exception.NaoPossivelConectarException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class PanelConnect extends javax.swing.JPanel implements JanelaListener {

    /**
     * Creates new form ConnectPanel
     */
    public PanelConnect(Frame base) {
        this.base = base;
        initComponents();
        bCancel.setVisible(false);
        this.atorJogador = base.getJogador();
        this.atorJogador.setConnectPanel(this);
    }
    AtorJogador atorJogador = null;
    Frame base = null;

    private void notifyParentFrame() {
        base.changePanels("Tabuleiro");
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tNomeTecnico = new javax.swing.JTextField();
        bConnect = new javax.swing.JButton();
        tMessage = new javax.swing.JLabel();
        bCancel = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setBackground(new java.awt.Color(202, 227, 247));

        bConnect.setText("Conectar");
        bConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bConnectActionPerformed(evt);
            }
        });

        bCancel.setText("Cancelar");
        bCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelActionPerformed(evt);
            }
        });

        jLabel2.setText("Escreva seu nome:");

        jLabel1.setIcon(new javax.swing.ImageIcon(System.getProperty("user.dir")+"/resources/logo.jpg"));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(444, 444, 444)
                        .addComponent(tMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(tNomeTecnico, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(bConnect)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(bCancel)))
                                .addGap(82, 82, 82)
                                .addComponent(jLabel1)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(tMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(tNomeTecnico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(bConnect)
                                            .addComponent(bCancel)))
                                    .addComponent(jLabel1))))
                        .addGap(0, 337, Short.MAX_VALUE)))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void bConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bConnectActionPerformed
        String nome = tNomeTecnico.getText();
        atorJogador.setNomeUsuario(nome);
        boolean isConectado = false;
        try {
            isConectado = atorJogador.conectar();//<<<<<<<<<<<
        } catch (JahConectadoException ex) {
            Logger.getLogger(PanelConnect.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Já Conectado!", JOptionPane.ERROR_MESSAGE);
        } catch (NaoPossivelConectarException ex) {
            Logger.getLogger(PanelConnect.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Não foi possível Conectar", JOptionPane.ERROR_MESSAGE);
        } catch (ArquivoMultiplayerException ex) {
            Logger.getLogger(PanelConnect.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
        }
        if (isConectado) {
            try {
                atorJogador.iniciarPartida();
            } catch (NaoConectadoException ex) {
                Logger.getLogger(PanelConnect.class.getName()).log(Level.SEVERE, null, ex);

            }
            bConnect.setEnabled(false);
            tNomeTecnico.setEnabled(false);
            bCancel.setVisible(true);
            tMessage.setText("Aguardando segundo jogador para iniciar partida ...");
        }
    }//GEN-LAST:event_bConnectActionPerformed

    private void bCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelActionPerformed
        resetarComponentes();
        atorJogador.desconectar();
    }//GEN-LAST:event_bCancelActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bCancel;
    private javax.swing.JButton bConnect;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel tMessage;
    private javax.swing.JTextField tNomeTecnico;
    // End of variables declaration//GEN-END:variables

    @Override
    public void waitFinished() {
        this.notifyParentFrame();
        resetarComponentes();
    }

    @Override
    public void connectionLost(String msg) {
        atorJogador.desconectar();
    }

    private void resetarComponentes() {
        bConnect.setEnabled(true);
        tNomeTecnico.setEnabled(true);
        bCancel.setVisible(false);
        tMessage.setText("");
    }
}
